<?php
namespace plugins\goods\controller;
use cmf\controller\ApiThirdAccessBaseController;
use plugins\goods\model\GoodsBrowseModel;
use plugins\goods\model\GoodsModel;
use plugins\store\model\StoreModel;
use think\Db;
use plugins\member\interfaceLib\MemberClassify;
class ApiCommonController extends ApiThirdAccessBaseController
{
    protected $recommend_num = 6; // 推荐显示的商品数量
    protected $model; //模型
    protected $uid = '';
    /**
     * 初始化
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new GoodsModel();
        $data = $this->request->param();
        if(!empty($data['aes'])){
            $this->uid = ( new MemberClassify )->aesGetUid($data['aes']);
        }else{
            $this->uid = '';
        }
        $this->model->where([
            'is_del'       => ['<>', 1], //删除状态
            'audit_status' => 2, //审核状态
            'status'       => 1, //上架状态
        ]);
    }
    /**
     * 商品列表
     */
    public function goodsList()
    {
        $data = $this->request->post();
        checkParam(['type_sort', 'pageNum', 'page'], $data);
        $uid   = $this->uid;
        $where = 1;
        if (!empty($data['store']) && $data['store'] == true) {
            $store = (new StoreModel)->get(['uid' => $uid]);
            if ($store == null) {
                return api_json_echo(false, '该账号下未拥有店铺，请申请');
            }
            $data['store_id'] = $store->store_id;
        }
        if (!empty($data['store_id'])) {
            $where .= " and store_id='" . $data['store_id'] . "'";
        }
        if (!empty($data['store_name'])) {
            $where .= " and store_name like '%" . $data['store_name'] . "%'";
        }
        //如果完整匹配到分类名,关键字不检索商品名
        $catid = Db::name( 'goods_cats' )->where( 'catname' , 'like' , $data['goods_name'] )->value(  'catid' );
        if( !empty( $catid ) ){
            $data['catid'] = $catid ;
            $data['goods_name'] = '' ;
        }
        if (!empty($data['catid'])) {
 
            $where .= " and catid = ".$data['catid'];
        }
        if (!empty($data['goods_name'])) {
            //添加搜索记录
            $this->model->addSearchRecord($uid, $data['goods_name']);
            $where .= " and goods_name like '%" . $data['goods_name'] . "%'";
        }
        $order = "";
        switch ($data['type_sort']) {
            case 1: //综合排序
                break;
            case 2: //上架时间筛选倒序
                $order = "upward_time desc";
                break;
            case 3: //上架时间筛选正序
                $order = "upward_time";
                break;
            case 4: //价格降序
                $order = "shop_price desc";
                break;
            case 5: //价格升序
                $order = "shop_price";
                break;
            case 6: //销量排序 从大到小
                $order = "sell_num desc";
                break;
            case 7: //销量排序 从小到大
                $order = "sell_num";
                break;
            default:
                break;
        }
        //价格区间筛选
        if (!empty($data['start_price'])) {
            $where .= " and shop_price <= " . $data['start_price'];
        }
        if (!empty($data['end_price'])) {
            $where .= " and shop_price >= " . $data['end_price'];
        }
        $list = $this->model
            ->where($where)
            ->order($order)
            ->paginates($data['pageNum'], '', ['page' => $data['page']])
            ->each(function ($item) {
                $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
                return $item;
            })->toArray();
        return api_json_echo(true, 'success', $list, 200);
    }
    /**
     * 商品详情
     */
    public function goodsDetail()
    {
        $data = $this->request->post();
        checkParam(['id'], $data);
        $uid   = $this->uid;
        $where = [
            'id' => ['=', $data['id']],
        ];
        $list = $this->model->goodsDetail($where);
        if (empty($list)) {
            return api_json_echo(false, '商品不存在', null, -1);
        }
        //获取运费和地址信息
        $freight                  = $this->freight($data['id']);
        $list['freight_price']    = $freight['freight_price'];
        $list['shopping_address'] = $freight['shopping_address'];
        //获取销量和库存
        $sell_num          = $this->model->getSellinventory($data['id']);
        $list['sell_num']  = $sell_num['sell_num']; //销量
        $list['inventory'] = $sell_num['inventory']; //库存
        //获取三十天内的浏览量
        $browse_num         = (new GoodsBrowseModel)->getBrowseNum($data['id'], 30);
        $list['browse_num'] = $browse_num;
        //判断商品是否收藏
        $is_collect         = Db::name('goods_collect')->where('uid', $uid)->where('goods_id', 'like', "%," . $data['id'] . ",%")->find();
//        var_dump(Db::name('goods_collect')->getLastSql());
        $list['is_collect'] = !empty($is_collect) ? true : false;
        $list['price_explain'] = '参考价：商品展示的划线价或参考价可能是品牌专柜价、商品吊牌价或由品牌供应商提供的正品零售价（如厂商指导价、建议零售价等）或该商品在考拉上曾经展示过的销售价；由于地区、时间的差异性和市场行情波动，品牌专柜标价、商品吊牌价等可能会与您购物时展示的不一致，该价格仅供您参考。
促销价：如无特殊说明，促销价是销售商在参考价基础上给予的优惠价格。如有疑问，您可以在购买前与客服联系。';
        \think\Hook::exec('\\plugins\\goods\\common\\GoodsHook', '', $uid, $list); //足迹
        \think\Hook::exec('\\plugins\\goods\\common\\GoodsBrowseHook', '', $uid, $data['id']); //浏览量
        return api_json_echo(true, 'success', $list, 200);
    }
    /**
     * 获取运费 和 运送地址信息
     */
    private function freight($gid)
    {
        //获取商品信息
        $goods = $this->model->where('id', $gid)->find();
        $freight_price    = 0;
        $shopping_address = [
            'receive_name'  => '',
            'receive_phone' => '',
            'cri_name'      => '东城区',
            'cri_code'      => '310101',
            'address'       => '北京市东城区',
            'postal_code'   => '',
            'show_address'  => [
            ]
        ];
        if (!empty($this->uid)) {
            try {
                $address = new \plugins\member\model\MemberShipAddressModel;
                $address = $address->where(['uid' => $this->uid, 'is_default' => 1])->find();
                if (!empty($address)) {
                    $address['show_address'] = json_decode($address['show_address'], true);
                    $shopping_address = $address;
                }
            } catch (\Exception $e) {
            }
        }
        //省（计算运费）
        $province = '北京';
        if (!empty($shopping_address['show_address'])) {
            $show_address = $shopping_address['show_address'];
            //排序
            sort($show_address);
            $province = $show_address[0];
        }
        $fei = [
            'freight_id' => $goods['freight_id'],
            'province' => $province,
            'goods_num' => 1,
            'store_id' => $goods['store_id'],
        ];
        try {
            $yun = $this->model->getFreight($fei);
            if ($yun['status'] == 'success') {
                //待计算运费
                $freight_price = $yun['data']['freight_price'];
            }
        } catch (\Exception $e) {

        }
        $da = [
            'shopping_address' => $shopping_address,
            'freight_price'    => $freight_price,
        ];
        return $da;
    }
    /**
     * 推荐喜欢商品
     */
    public function likeGoods()
    {
        $data = $this->request->post();
        checkParam(['pageNum', 'page'], $data);
        $list = $this->model->where('referr_status', 1)
            ->order('add_time desc')
            ->limit($this->recommend_num)
            ->paginate($data['pageNum'], false, ['page' => $data['page']])
            ->each(function ($item) {
                $detail_img = json_decode($item['detail_img'], true) ?: [];
                foreach ($detail_img as $key => &$value) {
                    $value = zy_domain() . $value;
                }
                $item['detail_img'] = $detail_img;
                return $item;
            })->toArray();
        return api_json_echo(true, 'success', $list, 200);
    }
}
